package com.gitee.chessboard;

import com.gitee.chessboard.jdbc.JdbcManager;
import com.gitee.chessboard.manager.DefaultDictionaryManager;
import com.gitee.chessboard.manager.DictionaryManager;
import com.gitee.chessboard.parser.ConstantDictionaryParser;
import com.gitee.chessboard.parser.DefaultConstantDictionaryParser;
import com.gitee.chessboard.parser.DefaultEnumDictionaryParser;
import com.gitee.chessboard.parser.EnumDictionaryParser;
import com.gitee.chessboard.properties.DictionaryProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 字典模块的自动配置入口
 *
 * @author 敲代码的旺财
 * @date 2021/11/17 16:18
 **/
@Configuration
@ComponentScan("com.gitee.chessboard")
public class DictionaryAutoConfiguration {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Value("${spring.chessboard.dictionary.scan}")
    private String dictionaryScan;

    @Bean
    public JdbcManager jdbcManager(SqlSessionFactory mybatisSqlSessionFactory) {
        JdbcManager jdbcManager = new JdbcManager(
                dataSourceProperties.getDriverClassName()
                , dataSourceProperties.getUrl()
                , dataSourceProperties.getUsername()
                , dataSourceProperties.getPassword());
        jdbcManager.setMybatisSqlSessionFactory(mybatisSqlSessionFactory);
        return jdbcManager;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.chessboard.dictionary")
    public DictionaryProperties dictionaryProperties() {
        return new DictionaryProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    public DictionaryManager dictionaryManager(JdbcManager jdbcManager) {
        return new DefaultDictionaryManager(jdbcManager, dictionaryScan);
    }

    @Bean
    @ConditionalOnMissingBean
    public EnumDictionaryParser enumDictionaryParser(DictionaryManager dictionaryManager) {
        return new DefaultEnumDictionaryParser(dictionaryManager);
    }

    @Bean
    @ConditionalOnMissingBean
    public ConstantDictionaryParser constantDictionaryParser(DictionaryManager dictionaryManager) {
        return new DefaultConstantDictionaryParser(dictionaryManager);
    }


}
